package com.apes.scm.masterdata.frame.repository;

import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.scm.masterdata.frame.model.BranchEntry;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.merchant.model.Merchant;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Map;

public interface StoreRepository extends CustomRepository<Store, String> {

    @Query("select s " +
            "from Store s where to_char(s.lastUpdatedStamp,'yyyy-mm-dd hh24:mi:ss.ff3' ) > :times or (s.id > :id and to_char(s.lastUpdatedStamp,'yyyy-mm-dd hh24:mi:ss.ff3' ) = :times)  " +
            " order by s.lastUpdatedStamp, s.id asc ")
    List<Store> findAllStoreByTs(@Param("times") String times, @Param("id") String id, Pageable pageable);

    Store findByBranchEntry(BranchEntry branchEntry);

    @Query("select T from Store T where (T.id like %:value%  or T.name like %:value%) ")
    List<Store> findLikeName( @Param("value") String value);

    @Query("select T from Store T where (T.id like %:value%  or T.name like %:value%) and T.containSpace = true")
    Page<Store> findLikeName2(@Param("value") String value, Pageable pageable);

    Store findByDept(Dept dept);

    Store findByCode(String code);

    @Query("select s " +
            "from Store s where s.upCarRepair = true and s.carRepairNumber is not null and s.carRepairPassword is not null ")
    List<Store> findByAllIsUpCarRepair();

    List<Store> findAllByMerchant(Merchant merchant);

    @Query("select T from Store T where T.code = :code")
    Store findByStoreCode(@Param("code") String code);

    @Query("select T.dept from Store T where T.containSpace = true")
    List<Dept> findAllDeptByContainSpace();

    @Query(value = "select A.id as ID, A.name as name, A.address as address, B.id as deptId from mas_store A,mas_dept B where (A.id like %:value%  or A.name like %:value%) AND A.dept_id = B.ID AND B.valid = 1",nativeQuery = true)
    List<Map<String, Object>> queryDeptByValue(@Param("value") String value);

    @Query(value = "select A.id as ID, A.name as name, A.address as address, B.id as deptId from mas_store A,mas_dept B where A.dept_id = B.ID AND B.valid = 1",nativeQuery = true)
    List<Map<String, Object>> queryDeptAll();
}
